package org.dubnation.auth.service.impl;

import org.dubnation.auth.domain.SysWebLogin;
import org.dubnation.auth.domain.dto.LoginDTO;
import org.dubnation.auth.domain.vo.LoginVO;
import org.dubnation.auth.service.ILoginService;
import org.dubnation.base.enums.ResponseCode;
import org.dubnation.base.exception.BusinessException;
import org.dubnation.base.util.audit.DubnationAssert;
import org.dubnation.base.util.encryption.MD5Utils;
import org.dubnation.user.domain.LoginInfo;
import org.dubnation.user.mapper.LoginInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class LoginServiceImpl implements ILoginService {

    @Autowired(required = false)
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private LoginVO loginVO;

    @Autowired
    private SysWebLogin sysWebLogin;

    /**
     * 登录
     * @param loginDTO
     * @return
     */
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        //1.判断当前登录人员是否已注册, 若未注册提醒其注册
        LoginInfo loginInfo = loginInfoMapper.queryByUsernameOrPhoneOrEmail(loginDTO.getUsername());
        if (loginDTO.getType().equals(LoginInfo.TYPE_ADMINISTRATORS)){
            DubnationAssert.isNotNull(loginInfo, ResponseCode.RESPONSE_CODE_4000032);
        }else {
            DubnationAssert.isNotNull(loginInfo, ResponseCode.RESPONSE_CODE_4000031);
        }
        //2.若已注册查询注册信息, 进行密码比对
        DubnationAssert.isEq(MD5Utils.encryptionByMd5("kisc1130" + loginInfo.getSalt() + loginDTO.getPassword()),
                loginInfo.getPassword(), ResponseCode.RESPONSE_CODE_4000017);
        //3.生成token将用户/管理员信息存入redis并返回前端做免密登录
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(token, loginInfo, 5, TimeUnit.MINUTES);
        loginVO.setToken(token);
        sysWebLogin.setUsername(loginInfo.getUsername());
        sysWebLogin.setEmail(loginInfo.getEmail());
        sysWebLogin.setPhone(loginInfo.getPhone());
        loginVO.setSysWebLogin(sysWebLogin);
        return loginVO;
    }
}
